package com.xwder.summary.collection.array;

import java.util.Arrays;

/**
 * array copy 四种方法
 * @author xwder
 */
public class TestArrayCopy {
    
    /**
     * System.arraycopy
     * @param original 原数组
     */
    public static void testSystemArrayCopy(String[] original) {
        long startTime = System.nanoTime();
        String[] target = new String[original.length];
        System.arraycopy(original, 0, target, 0, target.length);
        long endTime = System.nanoTime();
        System.out.println("使用System.arraycopy方法耗时:" + (endTime - startTime));
 
    }

    /**
     * Arrays.copyOf
     * @param original 原数组
     */
    public static void testArraysCopyOf(String[] original) {
        long startTime = System.nanoTime();
        String[] target = new String[original.length];
        target = Arrays.copyOf(original, original.length);
        long endTime = System.nanoTime();
        System.out.println("使用Arrays.copyOf方法耗时:" + (endTime - startTime));
    }

    /**
     * clone()
     * @param original 原数组
     */
    public static void testClone(String[] original) {
        long startTime = System.nanoTime();
        String[] target = new String[original.length];
        target = original.clone();
        long endTime = System.nanoTime();
        System.out.println("使用clone方法耗时:" + (endTime - startTime));
    }

    /**
     * foreach copy
     * @param original 原数组
     */
    public static void testFor(String[] original) {
        long startTime = System.nanoTime();
        String[] target = new String[original.length];
        for (int i = 0; i < original.length; i++) {
            target[i] = original[i];
        }
        long endTime = System.nanoTime();
        System.out.println("使用for循环耗时:" + (endTime - startTime));
    }
 
    public static void main(String[] args) {
        //需要改变原始数组的大小
        String[] original = new String[100];

        // 所有元素赋值为同一个值
        Arrays.fill(original, "abcd");

        System.out.println("原始数组的大小:" + original.length);
        testSystemArrayCopy(original);
        testArraysCopyOf(original);
        testClone(original);
        testFor(original);
    }
}

